package com.etong.citymap.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.widget.ImageView;
import android.widget.Toast;

import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.util.MapInfoUtil;
import com.etong.citymap.util.log.LogDetailUtil;
import com.etong.citymap.util.log.LogUtil;
import com.supermap.data.CursorType;
import com.supermap.data.DatasetVector;
import com.supermap.data.Environment;
import com.supermap.data.Geometry;
import com.supermap.data.Point;
import com.supermap.data.Point2D;
import com.supermap.data.QueryParameter;
import com.supermap.data.Recordset;
import com.supermap.data.Workspace;
import com.supermap.data.WorkspaceConnectionInfo;
import com.supermap.data.WorkspaceType;
import com.supermap.mapping.CallOut;
import com.supermap.mapping.CalloutAlignment;
import com.supermap.mapping.Layer;
import com.supermap.mapping.Layers;
import com.supermap.mapping.MapControl;
import com.supermap.mapping.MapView;

import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

/**
 * 地图控件
 */
public class MapActivity extends Activity {
	/** 定时自动GPS定位成功 */
	public static final int MSG_AUTO_LOCATION_OK = 100;
	/** 返回Activity消息 */
	public static final int MSG_RESUME = 7;
	/** 地图加载成功 */
	public static final int MSG_MAP_LOADED = 2;
	public static final String AUTO_LOCATION = "AUTO_LOCATION";
	private MapControl mapControl;
	private Workspace workspace;
	private WorkspaceConnectionInfo info;
	private GestureDetector gestureDetector;
	ImageView locImage;
	AlertDialog dialog;
	Point2D locPoint = null;
	Point2D autoLocPoint = null;
	private CallOut myLocation;
	private Handler handle;
	private MapView mapView;
	public CallOut preLocation = null; // 传过来的坐标位置标注
	private boolean isCenter = false; // 用于定位点移到屏幕中心
	private boolean returnResult = false;

	private Point2D prePoint;
    private final String SDPath=android.os.Environment.getExternalStorageDirectory().getAbsolutePath();
	private CityApplication cityApplication;
	
	private boolean isFirst = false; //是否首次打开

	private String bgcode; //单元网格背景编码
	private String commName; //单元风格社区名称

	private Activity myAcitivity;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		myAcitivity = this;

		handle = new Handler(new UpdateMapHandler());
		cityApplication = (CityApplication)getApplication();
		dialog = new ProgressDialog(this);
		dialog.setTitle(null);
		dialog.setCanceledOnTouchOutside(false);
		dialog.setMessage("正在初始化数据...");
		dialog.show();

		isFirst = true;
		if (this.getIntent().getExtras() != null) {
			Double x = this.getIntent().getExtras().getDouble("x");
			Double y = this.getIntent().getExtras().getDouble("y");
			returnResult = getIntent().getExtras().getBoolean("result");
			if (!x.equals(0.0) && !y.equals(0.0)) {
				prePoint = new Point2D(x, y);
			}
		}

		new Thread(new LoadMapRunable()).start();
	}

	private void initUI() {
		setContentView(R.layout.map);
		mapView = findViewById(R.id.mapview);
		ImageView loc = findViewById(R.id.nav_normal);
		loc.setOnClickListener(v -> {
			Toast.makeText(getApplicationContext(), "正在定位，请稍候！",Toast.LENGTH_SHORT).show();
			Point2D locPoint = MapInfoUtil.get2DLocation4Supermap(myAcitivity);
			LogDetailUtil.i("MapActivity通过手动的方式获得的定位信息！Point2D=" + locPoint);
			if (locPoint == null) {
				Toast.makeText(getApplicationContext(), "定位失败，请检查GPS设置！",Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(getApplicationContext(), "定位成功！",Toast.LENGTH_SHORT).show();
				isCenter = true;
				mapControl.getMap().setCenter(locPoint);//设置坐标点为中心
				setLocation(locPoint);
				prePoint = locPoint;
				setSelectInfo( );
			}
		});
		new Timer().schedule(new TimerTask(){
			public void run() {
				try {
					autoLocPoint = MapInfoUtil.get2DLocation4Supermap(myAcitivity);
					LogDetailUtil.i("MapActivity通过定时功能获得的定位信息！Point2D=" + autoLocPoint);
					if(null != autoLocPoint){
						handle.sendEmptyMessage(MSG_AUTO_LOCATION_OK);
					}
				} catch (Exception e) {
					LogUtil.e(e);
				}
			}}, 2000,2000); //延迟5秒之后，每5秒循环添加轨迹
	}

	private void setLocation(Point2D locPoint) {
		if (myLocation == null) {
			myLocation = new CallOut(MapActivity.this);
			myLocation.setStyle(CalloutAlignment.CENTER);
			myLocation.setCustomize(true);
			locImage = new ImageView(MapActivity.this);
			myLocation.setContentView(locImage);
			locImage.setBackgroundResource(R.drawable.loc1);
		}
		mapView.removeCallOut(AUTO_LOCATION);
		mapView.addCallout(myLocation,AUTO_LOCATION);
		myLocation.setLocation(locPoint.getX(), locPoint.getY());//移动坐标点位置
		mapControl.getMap().refresh();
	}

	// 接收长按事件
	private SimpleOnGestureListener mGestrueListener = new SimpleOnGestureListener() {

		public void onLongPress(MotionEvent e) {
		}

		@Override
		public boolean onSingleTapUp(MotionEvent e) {
			if (returnResult) {
				int x = (int) e.getX();
				int y = (int) e.getY();
				prePoint = mapControl.getMap().pixelToMap(new Point(x, y));
				setSelectInfo( );
			}

			return super.onSingleTapUp(e);
		}

		@Override
		public boolean onDown(MotionEvent e) {
			return super.onDown(e);
		};

	};

	private void setSelectInfo( ) {
		LogDetailUtil.i("选择了新的位置信息：" + prePoint);
		if (prePoint != null) {
			if(preLocation == null) {
				preLocation = new CallOut(MapActivity.this);
				ImageView iv = new ImageView(MapActivity.this);
				iv.setBackgroundResource(R.drawable.nav_turn_via_1_s);
				preLocation.setStyle(CalloutAlignment.BOTTOM);
				preLocation.setCustomize(true);
				preLocation.setContentView(iv);
				//mapView.removeAllCallOut();
				mapView.addCallout(preLocation);
			}
			preLocation.setLocation(prePoint.getX(), prePoint.getY());
			Layers la = mapControl.getMap().getLayers();
			int i = la.getCount();
			Layer layer = la.get("保洁公司@WuhuCity");//之前的WM系统，不用加@whx，现在要加whx,不过我这边不需要处理。
			DatasetVector datasetvector = (DatasetVector)layer.getDataset();

			 // 设置查询参数
			QueryParameter parameter = new QueryParameter();
			parameter.setCursorType(CursorType.STATIC);

			// 查询，返回查询结果记录集
			Recordset recordset = datasetvector.query(parameter);
			int j = 0;
			boolean b = false;
			int commid = -1;
			Geometry geometry = null;
			while (!recordset.isEOF()) {
				geometry = recordset.getGeometry();
				b = geometry.hitTest(prePoint, 0d);
				if(b) {
					commid = geometry.getID();
					bgcode = recordset.getString("SMID");
					commName = recordset.getString("name");
					break;
				}
				recordset.moveNext();
				j++;
			}
			recordset.dispose();
			if(geometry!=null) geometry.dispose();
			Toast.makeText(MapActivity.this, "定位成功", Toast.LENGTH_SHORT) .show();
		}
	}

	protected void onResume() {
		returnResult = cityApplication.isReturnResult();
		prePoint = cityApplication.getPrePoint();
		cityApplication.setPrePoint(null);
		if(isFirst)
			isFirst=false;
		else
			handle.sendEmptyMessage(MSG_RESUME);
		super.onResume();
	};
	
	@Override
	protected void onPause() {
		super.onPause();
	}
	
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		// 是否触发按键为back键
		if (keyCode == KeyEvent.KEYCODE_BACK && returnResult) {
			// 实例化 Bundle，设置需要传递的参数
			if (prePoint != null) {
				cityApplication.setLocPoint(prePoint);
				if(bgcode != null && !"".equals(bgcode.trim())){
					cityApplication.setBgCode(bgcode);
				}
				if(commName != null && !"".equals(commName.trim())) {
					cityApplication.setCommName(commName);
				}
			} else if (prePoint == null && locPoint != null) {
				cityApplication.setLocPoint(locPoint);
			} else {
				setResult(RESULT_OK);
			}
			//this.finish();
			prePoint = null;
			moveTaskToBack(true);
			return true;
		} else {
			prePoint=null;
			moveTaskToBack(true);
			return true;

		}
	}

	private class LoadMapRunable implements Runnable {
		@Override
		public void run() {
			try {// 设置一些系统需要用到的路径
				Environment.setLicensePath(SDPath + MapActivity.this.getResources().getString(R.string.city_license));
				Environment.setTemporaryPath(SDPath + MapActivity.this.getResources().getString(R.string.city_temppath));
				Environment.setWebCacheDirectory(SDPath + MapActivity.this.getResources().getString(R.string.city_webcache));
				Environment.initialization(MapActivity.this);
				if (workspace == null) {// 打开工作空间
					workspace = new Workspace();
				}
				if (info == null) {
					info = new WorkspaceConnectionInfo();
					info.setServer(SDPath + MapActivity.this.getResources().getString(R.string.city_server));
					info.setType(WorkspaceType.SMWU);
					workspace.open(info);
				}
				handle.sendEmptyMessage(MSG_MAP_LOADED);
			} catch (Exception e) {
				LogUtil.e(e);
			}
		}

	}

	// 专门更新地图用的
	private class UpdateMapHandler implements Handler.Callback {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == MSG_MAP_LOADED) {
				// 将地图显示控件和 工作空间关联
				initUI();
				mapControl = mapView.getMapControl();
				mapControl.getMap().setWorkspace(workspace);
				// 打开工作空间中地图的第1幅地图
				String mapName = workspace.getMaps().get(0);
				mapControl.getMap().open(mapName);
				if (prePoint != null) {
					if(preLocation == null){
						preLocation = new CallOut(MapActivity.this);
						preLocation.setLocation(prePoint.getX(), prePoint.getY());
						ImageView iv = new ImageView(MapActivity.this);
						iv.setBackgroundResource(R.drawable.nav_turn_via_1_s);
						preLocation.setStyle(CalloutAlignment.BOTTOM);
						preLocation.setCustomize(true);
						preLocation.setContentView(iv);
						mapView.addCallout(preLocation);
					}
					mapControl.getMap().setCenter(prePoint);
				}
				mapControl.getMap().refresh();
				dialog.dismiss();

				// 设置手势委托
				if (gestureDetector == null) {
					gestureDetector = new GestureDetector(mGestrueListener);
				}
				mapControl.setGestureDetector(gestureDetector);

				//不通过此方法来循环获得定位信息
				//Message message = handle.obtainMessage(6);
				//handle.sendMessageDelayed(message, 1000);
			}
			if(msg.what==6){//不通过此方法来循环获得定位信息
//				locPoint = cityApplication.getGpsPoint();
//				if (locPoint == null){
//					return false;
//				}
//
//				if (isCenter) {
//					Point2D p = mapControl.getMap().getCenter();
//
//					mapControl.getMap().pan(locPoint.getX() - p.getX(),
//							locPoint.getY() - p.getY());
//					// mapControl.getMap().refresh();
//					isCenter = false;
//				}
//
//				getLocation();
//				myLocation.setLocation(locPoint.getX(), locPoint.getY());
//				mapView.refresh();
//				Message message = handle.obtainMessage(6);
//				handle.sendMessageDelayed(message, 1000);
			}
			
			if(msg.what== MSG_RESUME){
				//mapView.removeAllCallOut();
				myLocation = null;
				if (prePoint != null) {
					if(preLocation == null){
						preLocation = new CallOut(MapActivity.this);
						preLocation.setLocation(prePoint.getX(), prePoint.getY());
						ImageView iv = new ImageView(MapActivity.this);
						iv.setBackgroundResource(R.drawable.nav_turn_via_1_s);
						preLocation.setStyle(CalloutAlignment.BOTTOM);
						preLocation.setCustomize(true);
						preLocation.setContentView(iv);
						mapView.addCallout(preLocation);
					}
					mapControl.getMap().setCenter(prePoint);
				}
				mapControl.getMap().refresh();
				
			}
			if(msg.what== MSG_AUTO_LOCATION_OK){
				try {
					setLocation(autoLocPoint);
				} catch (Exception e) {
					LogUtil.e(e);
				}
			}
			return false;
		}
	}

	@Override
	protected void onDestroy() {
		cityApplication.setCreenDateTime(new Date().getTime());
		//new DestoryClass().start();
		super.onDestroy();
	}

	class DestoryClass extends Thread {

		@Override
		public void run() {
			try {
				if (mapControl != null) {
					mapControl.getMap().close();
					mapControl.dispose();
					mapControl = null;
				}
				if (info != null) {
					info.dispose();
					info = null;
				}
				if (workspace != null) {
					workspace.close();
					workspace.dispose();
					workspace = null;
				}
				System.gc();
			} catch (Exception e) {
				LogUtil.e(e);
			}
		}
	}

}
